<?php
namespace plugins\message_push\model;

/**
 * 小程序模板发送
 */
class Applet
{
    /**
     * 小程序模板发送
     */
    public function send_applet($param)
    {
        $data = [
            'canshu' => [
                'touser' => $param['openid'],
                'template_id' => $param['template_id'],
                'data' => $param['data'],
            ],
        ];
        //根据公司id查询
        $applet_config = db('applet_config')->where('company_id',$param['company_id'])->find();
        if(empty($applet_config)){
            return api_json_echo(false,'请先配置小程序信息');
        }
        $token = $this->getToken($param['company_id'],$applet_config['appid'],$applet_config['appSecret']);
        //模板消息发送接口
        $url = 'https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token='.$token;
        $fa = json_encode($data['canshu']);
        $common = new Common();
        $result = $common->https_request($url,$fa);
        return json_decode($result, true);
    }

    /**
     * 获取access_token的方法
     */
    public function getToken($company_id,$appid,$appSecret)
    {
        //获取公众号token
        $token = cache('access_token_applet_'.$company_id);
        if (!empty($token)) {
            return $token;
        }
        $common = new Common();
        $TOKEN_URL="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$appSecret;
        $TOKEN_URL = $common->https_request($TOKEN_URL);
        $result=json_decode($TOKEN_URL,true);
        if (isset($result['errcode'])) {
            return false;
        }
        cache('access_token_applet_'.$company_id,$result['access_token'],5000);
        return $result['access_token'];
    }

}